#include "PointLightEffect.h"

PointLightEffect::PointLightEffect(const LPDIRECT3DDEVICE9 device, EffectManager *effMgr, TextureManager *texMgr) :Effect(device, effMgr, texMgr)
{
}

PointLightEffect::~PointLightEffect(void)
{
}

void PointLightEffect::renderPointLight(Camera *camera, PointLight *pointLight, ModelMesh *sphereLight)
{
	device->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
	device->SetRenderTarget(0,* texMgr->getSurface(L"lightMap"));

	effMgr->setupEffect(DEF_POINT_LIGHT_FX);
	effMgr->getSetEffect()->SetTexture("colorMap" , texMgr->getTexture(L"colorMap"));
	effMgr->getSetEffect()->SetTexture("normalMap", texMgr->getTexture(L"normalMap"));
	effMgr->getSetEffect()->SetTexture("depthMap" , texMgr->getTexture(L"depthMap"));

	effMgr->getSetEffect()->SetMatrix("View", &camera->getViewMatrix());
	effMgr->getSetEffect()->SetMatrix("Projection", &camera->getProjMatrix());

	effMgr->getSetEffect()->SetVector("cameraPosition", &camera->getPosition4());
	effMgr->getSetEffect()->SetMatrix("InvertViewProjection", &camera->getInvViewProjMatrix());
	effMgr->getSetEffect()->SetVector("halfPixel", &commonValues::halfPixel);

	effMgr->getSetEffect()->SetMatrix("World", &pointLight->getWorldMatrix());
	effMgr->getSetEffect()->SetVector("lightPosition", &pointLight->getPosition4());
	effMgr->getSetEffect()->SetVector("Color", &pointLight->getColor());
	effMgr->getSetEffect()->SetFloat("lightRadius", pointLight->getRadius());
	effMgr->getSetEffect()->SetFloat("lightIntensity", pointLight->getIntensity());

	D3DXVECTOR4 diff;
	D3DXVec4Subtract(&diff, &pointLight->getPosition4(), &camera->getPosition4());
	FLOAT distance = D3DXVec4Length(&diff);

	if (distance < pointLight->getRadius() * 1.0f)
	{
		device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
	}
	else
	{
		device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
	}

	UINT numPasses;
	device->BeginScene();
	effMgr->getSetEffect()->Begin(&numPasses, 0);
	effMgr->getSetEffect()->BeginPass(0);
	sphereLight->getMesh()->DrawSubset(0);
	effMgr->getSetEffect()->EndPass();
	effMgr->getSetEffect()->End();
	device->EndScene();

	device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
	device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
}